package com.chen.hotel.controller;


import com.chen.hotel.Service.OrderService;
import com.chen.hotel.Service.WebSocket;
import com.chen.hotel.VO.ResultVO;
import com.chen.hotel.annotation.LoginToken;
import com.chen.hotel.domain.Order;
import com.chen.hotel.exception.HotelException;
import com.chen.hotel.utils.ResultVOUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RestController
@RequestMapping("/order")
@Slf4j
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WebSocket webSocket;

    /**
     * 创建一个订单
     */
    @PostMapping("")
    public ResultVO createOrder(@RequestBody Order order){
        webSocket.sendMessage("您有新的订单来了");
        log.info(order.toString());
        return ResultVOUtil.success(this.orderService.create(order));
    }

    /**
     * 取消一个订单
     */
    @GetMapping("/cancel/{id}")
    public ResultVO cancelOrder(@PathVariable Integer id, @RequestParam(value = "card") String card){
        if(StringUtils.isEmpty(card)){
            throw new HotelException(401, "您的参数传递有误");
        }
        this.orderService.cancel(id, card);
        return ResultVOUtil.success(null);
    }

    /**
     * 查询一个订单: 这里是不安全的，由于没有单独设立用户表， 没法对用户进行认证。
     */
    @GetMapping("/{id}")
    public ResultVO findById(@PathVariable Integer id){
        return ResultVOUtil.success(this.orderService.findById(id));
    }

    /**
     * 查询所有订单
     */
    @GetMapping("")
    @LoginToken
    public ResultVO getOrderAll(@RequestParam(value = "page", defaultValue = "0") Integer page,
                                     @RequestParam(value = "size", defaultValue = "10") Integer size){
        PageRequest request = PageRequest.of(page, size);
        return ResultVOUtil.success(this.orderService.findAll(request));
    }

    /**
     * 更新一个订单的状态
     */
    @PutMapping("/{id}")
    @LoginToken
    public ResultVO updateOrderStatus(@PathVariable Integer id, @RequestParam(value = "status") Integer status){
        if(status == null){
            throw new HotelException(401, "您的参数传递有误");
        }
        return ResultVOUtil.success(this.orderService.updateStatus(status, id));
    }

    /**
     * 获取某状态的订单列表:
     */
    @GetMapping("/list/{status}")
    @LoginToken
    public ResultVO getOrderByStatus(@PathVariable Integer status,
                                     @RequestParam(value = "page", defaultValue = "0") Integer page,
                                     @RequestParam(value = "size", defaultValue = "10") Integer size){
        PageRequest request = PageRequest.of(page, size);
        return ResultVOUtil.success(this.orderService.findByStatus(status, request));
    }

}
